#include "World.h"

static World* _World = nullptr;
static std::mutex WorldCreateLock;

World::World()
{
	_World = this;
}

World::~World()
{
}

World* World::GetInstance()
{
	if (!_World)
	{
		ThreadLocker Locker(WorldCreateLock);
		if (!_World)
			_World = new World();
	}
	return _World;
}

WorldSession* World::CreateNewSession(HSocket _socket)
{
	while (1)
	{
		WorldSession* TempSession = new WorldSession(_socket);
		ThreadLocker Locker(SessionMapLocker);
		SessionMap[_socket] = TempSession;
		return TempSession;
	}
}

void World::RemoveSession(HSocket _socket)
{
	while (1)
	{
		ThreadLocker Locker(SessionMapLocker);
		if (SessionMap.find(_socket) != SessionMap.end())
			SessionMap.erase(SessionMap.find(_socket));
		else {/*Log BUG;*/}
		return;
	}
}

WorldSession* World::FindSession(HSocket _socket)
{
	while (1)
	{
		ThreadLocker Locker(SessionMapLocker);
		if (SessionMap.find(_socket) != SessionMap.end())
			return SessionMap[_socket];
		else return nullptr;
	}
}